home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / devel / lang / lisp / guile-ii.src / guile-ii / guile-src / guile-docs / programmer / using-guile < prev   
Encoding:
Text File  |  1995-08-16  |  33.3 KB  |  1,154 lines

  1.  
  2.  
  3.  
  4.              USING GUILE IN YOUR PROGRAMS
  5.                 and
  6.           WRITING NEW BUILT-IN PROCEDURES AND TYPES
  7.  
  8.  
  9.  
  10.   INTRODUCTION
  11.   ============
  12.  
  13. This file will teach you how to make Guile the extension 
  14. language in your program.  It will show you:
  15.  
  16.     - How to initialize the interpreter.
  17.  
  18.     - Ways to call the interpreter to run extension programs or 
  19.       evaluate the code in C strings.
  20.  
  21.     - Ways to define new functions in C that are callable by Guile
  22.       programs.
  23.  
  24.     - Ways to define new data types in C that can be manipulated by
  25.       Guile programs.
  26.  
  27.  
  28. To bring this documentation to life, a more or less complete example
  29. of using Guile is needed.  None is ready for this first release of
  30. Guile, but one will be ready soon -- stay tuned for a version of Oleo
  31. that is extensible using Guile.
  32.  
  33.  
  34.  
  35.  
  36.   INVOKING GUILE FROM YOUR PROGRAM
  37.   ================================
  38.  
  39. * Compiling
  40.  
  41. If you use the functions and types described in this file, your 
  42. source files should include:
  43.  
  44.     #include "guile.h"
  45.  
  46. When you compile, you should link against the file `libguile.a'
  47. which is built and installed by this distribution.
  48.  
  49.  
  50.  
  51.  
  52. * Errors
  53.  
  54. Several functions return a value of type GSCM_status.  This type
  55. represents an error code.
  56.  
  57. The macro GSCM_OK is a value of type GSCM_status that is used
  58. to indicate success.  It is the normal return value of these
  59. functions.  Any other value indicates an error.
  60.  
  61. An error message can be generated from a GSCM_status value
  62. using the function gscm_error_msg.  Here is an example:
  63.  
  64.     GSCM_status status;
  65.  
  66.     status = initialize_gscm (0, argc, argv)
  67.     if (status != GSCM_OK)
  68.       {
  69.         fputs (gscm_error_msg (status), stderr);
  70.         fputc ('\n', stderr);
  71.         exit (1);
  72.       }
  73.  
  74. There is a specification that says all error messages must be an
  75. integral number of complete, punctuated, sentences.  If the message is
  76. more than one line, the first line will be a summary of the message.
  77. The message is not terminated by a newline.
  78.  
  79.  
  80.  
  81. * Initializing The Interpreter
  82.  
  83. Before calling any other Guile functions, you must initialize the
  84. state of the interpreter using this function:
  85.  
  86.  
  87.     GSCM_status
  88.     initialize_gscm (initfile, argc, argv)
  89.          char *initfile;
  90.          int argc;
  91.          char **argv;
  92.  
  93.     Initialize the internal state of the interpreter.
  94.  
  95.     This copies the arguments to be the return value of the Scheme
  96.     procedure `(program-arguments)'.
  97.     
  98.     This loads the Scheme code found at INITPATH.  If INITPATH is
  99.     NULL, the environment variable GUILE_INIT_FILE is checked.  If
  100.     that is empty, a built-in file name is used.  To prevent any
  101.     file from being evaluated, pass the value of the macro
  102.     GUILE_NO_INIT_FILE.  (In normal circumstances, you should pass
  103.     NULL and accept the user's or the library's default.)
  104.  
  105.     Normally this function returns GSCM_OK.  If the return value
  106.     is anything else, an error has occured.  (See the general
  107.     comments on errors, above).  If an error occurs, the interpreter
  108.     has not been initialized and may not be used.
  109.  
  110. Normally, you should only need to call this function once per
  111. invocation of your program.
  112.  
  113. There are exceptions to the rule that initialize_gscm must be called
  114. before any other gscm functions.  These exceptions are functions that
  115. supply extra parameters to the initialization process -- parameters for
  116. which the default should normally be reasonable.  These are:
  117.  
  118.     void gscm_verbosity (int n)
  119.     Set the level of verbosity.  See scm.texi about `(verbose n)'.
  120.  
  121.     void gscm_take_stdin ()
  122.     If this is called, then the interpreter will create a port 
  123.     called "*stdin*" that refers the stdio file FILE*, stdin.
  124.     On systems that permit it, buffering will be turned off for 
  125.     that stream.
  126.  
  127. The function initialize_gscm in turn calls the initialization function
  128. for all parts of libguile -- even those which may be considered
  129. optional.  If you want an interpreter with only a subset of the usual 
  130. functionality (perhaps to save on text size) you can use an alternative
  131. function to initialize gscm, gscm_init_from_fn:
  132.  
  133.     GSCM_status
  134.     gscm_init_from_fn (initfile, argc, argv, init_fn)
  135.          char *initfile;
  136.          int argc;
  137.          char **argv;
  138.          void (*init_fn) ();
  139.  
  140.  
  141.     Like initialize_gscm, but calls `init_fn' instead of 
  142.     directly calling initialization routines for optional
  143.     parts of libguile.
  144.  
  145.     init_fn may be a function you write, or one of the library
  146.     functions `guile_ks' or `guile_mini'.  `guile_ks' creates
  147.     a kitchen-sink interpreter, with all options turned on.
  148.     `guile_mini' creates a minimal interpreter.
  149.  
  150.     The currently available init functions (those called from
  151.     guile_ks) are:
  152.  
  153.       scm_init_ioext();
  154.       scm_init_posix();
  155.       scm_init_socket();
  156.       scm_init_unix();
  157.       scm_init_ioext();
  158.       scm_init_rgx();
  159.       scm_init_guile();
  160.       scm_init_ctax();
  161.       scm_init_tcl();
  162.       scm_init_tk();
  163.  
  164.  
  165. * Creating Top Levels
  166.  
  167. In order to evaluate expressions, you must provide a top level
  168. environment (aka global name-space) in which to evaluate the code.
  169. More than one top level environment may exist at a time.
  170.  
  171. There are two functions that relate to creating and releasing
  172. top levels:
  173.  
  174.  
  175.     
  176.     GSCM_status
  177.     gscm_create_top_level (GSCM_top_level * answer)
  178.  
  179.     Return a new top level environment.
  180.  
  181.     
  182.  
  183.     void
  184.     gscm_destroy_top_level (GSCM_top_level)
  185.  
  186.     Release all resources associated with a top level environment.
  187.  
  188.  
  189. When you release a top level environment using gscm_destroy_top_level,
  190. the data from the top level is not immediately freed.  Instead, all
  191. pointers to the information held on behalf of your application will be
  192. dropped, clearing the way for the top level to be garbage collected.
  193.  
  194.  
  195. * Invoking the Interpreter
  196.  
  197. There are two basic ways to invoke the interpreter: so that it 
  198. reads commands from a string, and so that it reads commands
  199. from a file.
  200.  
  201.     GSCM_status
  202.     gscm_eval_str (answer, toplvl, str)
  203.          char ** answer;
  204.          GSCM_top_level toplvl;
  205.          char * str;
  206.  
  207.     GSCM_status
  208.     gscm_eval_file (answer, toplvl, file_name)
  209.          char ** answer;
  210.          GSCM_top_level toplvl;
  211.          char * file_name;
  212.  
  213.     These forms return a newly allocated string in *answer.
  214.     The caller is responsible for freeing the string using `free'.
  215.  
  216.  
  217.   EXTENDING GUILE WITH NEW FUNCTIONS
  218.   ==================================
  219.  
  220. * Defining New Modules in C
  221.  
  222. As you add Guile to your programs, you will almost certainly want to
  223. define new procedures which can be called by extension programs.  This
  224. section will show you how.
  225.  
  226. Before introducing the functions, it is important to explain how
  227. Scheme objects are represented and how your code can manipulate the
  228. objects correctly.
  229.  
  230.  
  231.  
  232. * The Type `SCM'
  233.  
  234. Scheme data types are objects like pairs and closures which have
  235. special meaning to the interpreter.  To a C program, all such objects
  236. are of type SCM.
  237.  
  238. Two functions that return type SCM have already been described:
  239. gscm_seval_file and gscm_seval_str.  In the sections that follow,
  240. SCM values are used throughout.
  241.  
  242. There are some important conventions for manipulating SCM values.
  243. They are the subject of this section.
  244.  
  245. The type SCM is opaque to C programs.  It is not a structure, union,
  246. or pointer type (in fact, SCM is normally defined as a typedef for
  247. long integers, though you should not in any way rely on this fact in
  248. your code).  Values of type SCM are manipulated entirely by functions
  249. such as those documented in this file.
  250.  
  251. SCM objects are garbage collected.  That means that when the
  252. interpreter determines that the object is no longer needed, it is
  253. automaticly freed.  Very little explicit action is required from
  254. programmers to accomplish this.  You can be sure that GC will work
  255. correctly if you follow a few simple conventions.
  256.  
  257.   ****************************************
  258.   *                     * 
  259.   * IMPORTANT PROGRAMMING CONVENTIONS!!! *
  260.   *                     *
  261.   ****************************************
  262.  
  263. There are only three places where it is safe to store an SCM value.
  264.  
  265.     - in function arguments and local variables,
  266.  
  267.     - in an array allocated by gscm_mkarray,
  268.  
  269.     - in the fields of a Scheme object of a type
  270.       you are defining.
  271.  
  272. These are the only places properly searched by the garbage collector
  273. when deciding which Scheme objects may be discarded and which must
  274. live.
  275.  
  276. These rules imply that you can not store a Scheme value in a global
  277. variable or directly in malloced memory that is not part of a Scheme
  278. object.  Instead, you must store a pointer to an array allocated
  279. by gscm_mkarray, and store the SCM objects in that array.
  280.  
  281.  
  282.  
  283.   HEAP STORAGE FOR SCM VALUES: gscm_mkarray, gscm_free
  284.  
  285. It is generally not safe to store SCM values in malloced memory.
  286. (An exception to this is when the memory belongs to some Scheme
  287. object).  It is never safe to store SCM values in global C variables.
  288.  
  289. Instead, you can allocate storage for SCM values with this function:
  290.  
  291.     SCM *
  292.     gscm_mkarray (int num_elts);
  293.  
  294.     Return storage for NUM_ELTS of SCM values, all elements
  295.     initialized to GSCM_FALSE.
  296.  
  297.  
  298. To free memory allocated by gscm_mkarray, use
  299.  
  300.  
  301.     SCM
  302.     gscm_free (SCM *);
  303.  
  304.  
  305. So, for example, the following global declaration is wrong, because
  306. global storage is not one of the three places it is safe to store
  307. SCM values:
  308.  
  309.     SCM interesting_object_cache[10];    /* bogus */
  310.  
  311. but this code is correct, because storage allocated by gscm_mkarray
  312. is one of the three places it is safe to store SCM values.
  313.  
  314.     SCM *interesting_object_cache;
  315.  
  316.     init_module ()
  317.     {
  318.       interesting_object_cache = gscm_mkarray (10);
  319.       ...
  320.     }
  321.  
  322.  
  323. [In the future, support may be added for Scheme values which are represented
  324. by normal C global variables -- thus creating a fourth safe place to store
  325. SCM value.]
  326.  
  327. Function arguments, local variables, and the fields of
  328. application-defined Scheme objects (but *not* arrays returned by
  329. gscm_mkarray) are ``conservatively collected''.  That means that the
  330. garbage collector searches those areas for anything that looks like an
  331. SCM value, even if in fact it is not a value your program depends on
  332. any longer.
  333.  
  334. For that reason, it is a good idea to assign GSCM_FALSE (or some other
  335. neutral value) to SCM variables and structure fields which you are no
  336. longer using.
  337.  
  338.   
  339.  
  340.  
  341. * Defining new built-in procedures
  342.  
  343. The following procedure is used to define new built-in functions in 
  344. Guile.  It should be used only after initialize_gscm has been called.
  345.  
  346.  
  347.   void
  348.   guile_define_procedure (name, fn, req, opt, varp, doc)
  349.        char * name;
  350.        SCM val;
  351.        SCM (*fn)();
  352.        int req;
  353.        int opt;
  354.        int varp;
  355.        char * doc;
  356.  
  357.   This is the function used to turn a C function into a Scheme
  358.   procedure with a top level binding.
  359.   
  360.   NAME is the name the function will initially be given as a top level
  361.   binding.
  362.  
  363.   guile_define_procedure creates a procedure object that, when
  364.   invoked, results in a call to FN.  REQ and OPT specify the number of
  365.   required and optional parameters.  If VARP is true, the function
  366.   takes in addition a final argument -- a list of `rest' parameters.
  367.  
  368.     scm_obj = FN (req1, req2, ..., opt1, opt2, ..., rest_args)
  369.  
  370.   Note that parameters may be omitted.  For example, if OPT and VARP
  371.   are both 0, the function will simply be called:
  372.  
  373.     scm_obj = FN (req1, req2, ...reqn)
  374.  
  375.   passing only as many arguments as specified by the REQ parameter.
  376.  
  377.   Optional parameters that are not supplied by the caller are passed
  378.   the value GSCM_UNDEFINED.  If rest-arguments are requested, they are
  379.   passed as a scheme list.
  380.  
  381.   The total number of argument to the C function FN must not be
  382.   greater than 10.  If you need more arguments than that, write
  383.   a function that takes a variable number of argument (VARP == 1)
  384.   and explicitly check that the right number was passed by checking
  385.   the length of the list of rest arguments (use gscm_length).
  386.  
  387.   Tips for writing documentation are appended to this file.  The
  388.   documentation system has not been implemented yet, so nothing uses
  389.   these strings at present.  In addition to following the tips, a line
  390.   should be prepended to the doc-string that illustrates how the function
  391.   is called (see the example which follows).
  392.  
  393.   By convention, the string literal of a doc string should always be
  394.   enclosed in the macro GUILE_DOC.  This allows us, at a later time,
  395.   to find all of these strings automaticly.
  396.  
  397.   Here is a trivial example:
  398.  
  399.  
  400.     static char elisp_car_doc[] =
  401.         GUILE_DOC(
  402.         "(elisp-cdr list)
  403.     Return the cdr of CONSCELL.  If arg is nil, return nil.
  404.   
  405.     This function differs from Scheme CDR in it's treatment of the
  406.     empty list.
  407.         ");
  408.  
  409.     extern SCM e_cdr();
  410.         
  411.     void
  412.     elisp_initializer ()
  413.     {
  414.       gscm_define_procedure ("elisp-cdr", e_car, 1, 0, 0, elisp_car_doc);
  415.       ...
  416.     }
  417.  
  418.  
  419.  
  420. * Flow of Control in Built-in Functions
  421.  
  422. Calls to built-in Scheme functions have two properties that are unusual
  423. for C programs.  Programmer's must be aware of these when writing built-in
  424. functions:
  425.  
  426.   ******************************************
  427.   *                       * 
  428.   * IMPORTANT PROGRAMMING CONSIDERATION!!! *
  429.   *                       *
  430.   ******************************************
  431.  
  432.  
  433.     1. A built-in function may be aborted at almost any point
  434.        in its execution.
  435.  
  436.     2. A built-in function may be restarted any number of times
  437.        at almost any point in its execution.
  438.  
  439.  
  440. Here is why:
  441.  
  442. A built-in can be aborted at any time if:
  443.  
  444.     - it calls some other procedure that causes an error
  445.  
  446.     - an asynchronous interrupt causes an error
  447.  
  448.     - an interrupt or procedure call executes THROW to an
  449.       enclosing call to CATCH
  450.  
  451.     - a continuation which does not include the call to the built-in
  452.       can be invoked without first capturing the call to the built-in.
  453.  
  454.  
  455. A built-in can be restarted multiple times if a continuation is
  456. captured that includes the call to the built-in.  Such a continuation
  457. might be captured either asynchronously in an interrupt handler, or
  458. synchronously in a procedure call.  (Being captured asynchronously and
  459. restarted multiple times is highly unlikely -- if it happens, there is
  460. probably a bug in a user provided signal handler.  But consideration
  461. of the the possibility illustrates the kind of care that is necessary
  462. when writing new Scheme procedures in C.)
  463.  
  464. Here is an example of how you must plan for these possibilities:
  465.  
  466. Suppose you wanted to write a built-in procedure reads a block of data
  467. from a file, computes a checksum, and returns that checksum.  Before
  468. returning, it applies a hook procedure to the answer.  You might
  469. naively write this code:
  470.  
  471.  
  472.     /* Buggy code for a built-in function: */
  473.  
  474.     SCM
  475.     compute_checksum ()
  476.     {
  477.       char * data;
  478.       unsigned long sum
  479.  
  480.       /* Get a buffer filled with data: */
  481.       data = malloc (100);
  482.       read_data (data);
  483.  
  484.       /* Compute the checksum */
  485.       sum = compute_checksum (data);
  486.  
  487.       /* Call the hook function */
  488.       gscm_apply (checksum_hook, 
  489.               gscm_list (gscm_ulong (sum), GSCM_EOL_MARKER));
  490.  
  491.       free (data);
  492.  
  493.       return gscm_ulong (sum);
  494.     }
  495.  
  496. That function has several problems.  First, consider the call to gscm_apply.
  497. It is quite imaginable that the procedure bound to `checksum_hook' will
  498. capture its continuation, perhaps returning to that continuation more than
  499. once.  That means that `gscm_apply' may return more than once.
  500.  
  501. Suppose that it does.  Upon the first return, `data' is freed.  Upon
  502. the second return, the same `data' is freed a second time -- a
  503. catastrophic error.
  504.  
  505. On the other hand, gscm_apply might cause an error or find some other
  506. reason to never return.  In that case, `free' will never be called,
  507. and there is a core leak.
  508.  
  509. As a general rule, a built-in procedure can not be written to allocate
  510. and free resources in a linear fashion because the flow of control
  511. rules of Scheme make it difficult to ensure that the code will be
  512. executed just once, straight through.
  513.  
  514. As a first fix, you might try simply doing away with the hook function,
  515. since that is the mostly likely source of problems:
  516.  
  517.     /* Still buggy code for a built-in function: */
  518.  
  519.     SCM
  520.     compute_checksum ()
  521.     {
  522.       char * data;
  523.       unsigned long sum
  524.  
  525.       /* Get a buffer filled with data: */
  526.       data = malloc (100);
  527.       read_data (data);
  528.  
  529.       /* Compute the checksum */
  530.       sum = compute_checksum (data);
  531.  
  532.       free (data);
  533.  
  534.       return gscm_ulong (sum);
  535.     }
  536.  
  537. If that version worked, then you could call the built-in version
  538. %%compute-checksum and in your applications init file define:
  539.  
  540.     (define (compute-checksum)
  541.       (let ((answer (%%compute-checksum)))
  542.          (checksum-hook-fn answer)
  543.          answer))
  544.  
  545. This attempt would be the right idea: it is generally easier to code
  546. the problematic parts in Scheme, and to keep the C built-ins very simple.
  547. But alas, there is still a problem.
  548.  
  549. An asynchronous signal might come along during a call to
  550. compute_checksum.  In response, an arbitrary Scheme signal handler may
  551. be invoked.  When signal handlers are invoked, their continuation
  552. resumes execution of the interrupted function.  So, if the handler
  553. captures its continuation, parts of compute_checksum may be executed
  554. multiple times.  For example, an interrupt during the assignment to
  555. `sum' might once again lead to `free' being executed multiple times
  556. (or not be executed at all).
  557.  
  558. The problem of asynchronous interrupts can be quite serious.  For
  559. example, an interrupt during the call to `malloc' or `free' might
  560. leave the heap in an inconsistent state.
  561.  
  562. Here is yet a third version of `compute_checksum'.  This one works:
  563.  
  564.  
  565.  
  566.     /* Ahh...sweet mystery of liveness at last i've found you:
  567.          * (a version that works)
  568.      */
  569.     SCM
  570.     compute_checksum ()
  571.     {
  572.       char * data;
  573.       unsigned long sum
  574.  
  575.       GSCM_DEFER_INTS;
  576.  
  577.       /* Get a buffer filled with data: */
  578.       data = malloc (100);
  579.       read_data (data);
  580.       /* Compute the checksum */
  581.       sum = compute_checksum (data);
  582.       free (data);
  583.  
  584.       GSCM_ALLOW_INTS;
  585.  
  586.       return gscm_ulong (sum);
  587.     }
  588.  
  589. Two macros are used: GSCM_DEFER_INTS and GSCM_ALLOW_INTS.  These
  590. prevent asynchronous interruption.  Between calls to these macros,
  591. nothing surprising will happen with the flow of control.
  592.  
  593. There is an important restriction on the use of GSCM_DEFER_INTS
  594. and GSCM_ALLOW_INTS: you may not call any gscm functions between them
  595. For example, the first buggy example could not have been fixed by writing:
  596.  
  597.     /* Illegal because gscm_apply is called between GSCM_DEFER_INTS
  598.      * and GSCM_ALLOW_INTS:
  599.      */
  600.     GSCM_DEFER_INTS;
  601.     gscm_apply (checksum_hook, ...);
  602.     GSCM_ALLOW_INTS;
  603.  
  604.  
  605. In some circumstances, a more general sort of protection is called for
  606. than just GSCM_DEFER_INTS and GSCM_ALLOW_INTS.  Two functions defined
  607. below, gscm_catch and gscm_dynamic_wind provide to C programs the
  608. behavior of the Guile Scheme forms CATCH and DYNAMIC-WIND.
  609.  
  610.  
  611. [The documentation for this section makes it sound much more difficult
  612. than it really is, which is a bug since some people will be turned off
  613. just by the apparent complexity.  Also, call-with-dynamic-root allows
  614. people to write call-outs that don't have these surprises -- it needs
  615. to be documented as well.]
  616.  
  617.  
  618.  
  619.  
  620.   SCHEME PROCEDURES
  621.   =================
  622.  
  623. The next several sections describe functions that correspond to SCM
  624. procedures.  They are useful when writing new built-in functions.
  625.  
  626. The functions in this section should only be used from inside a
  627. built-in function.  In particular, they should not be used except
  628. while the interpreter is active.
  629.  
  630.  
  631. * gscm_cons, gscm_list
  632.  
  633. These functions are for manipulating lists.  
  634.  
  635.     SCM
  636.     gscm_cons (SCM a, SCM b)
  637.  
  638.     Allocate a new pair with A in the car and B in the cdr.
  639.  
  640.  
  641.  
  642.     SCM
  643.     gscm_list (SCM elt, ...)
  644.  
  645.     Allocate a new list containing the ELT arguments.
  646.  
  647.     The value GSCM_EOL_MARKER must be passed as the last argument to
  648.     gscm_list.  It is not included in the output list.
  649.  
  650.  
  651.     SCM gscm_set_car (SCM pair, SCM val)
  652.     SCM gscm_set_cdr (SCM pair, SCM val)
  653.     SCM gscm_car (SCM pair)
  654.     SCM gscm_cdr (SCM pair)
  655.  
  656.     Just what you would expect.  Also defined are gscm_caar, gscm_cadr
  657.     and so on for all `cxr' functions up to four elements long (e.e. cddddr).
  658.  
  659.  
  660.     int gscm_ilength (SCM obj)
  661.  
  662.     If OBJ is a proper list, return it's length.  Otherwise return -1.
  663.  
  664.  
  665.  
  666.  
  667. * gscm_ulong, gscm_long, gscm_double.
  668.  
  669. These functions convert some C number types to Scheme number types.
  670. C integers are converted to exact values.  C floating point numbers 
  671. are converted to inexact types.
  672.  
  673.     SCM
  674.     gscm_ulong (i)
  675.          unsigned long i;
  676.     SCM
  677.     gscm_long (i)
  678.          long i;
  679.     SCM
  680.     gscm_double (d)
  681.          double d;
  682.  
  683.     Convert a number to a Scheme object.
  684.  
  685.  
  686.  
  687.  
  688.  
  689. * gscm_2_long, gscm_2_ulong, gscm_2_double
  690.  
  691. These functions convert some Scheme number types into C number types.
  692.  
  693.     double
  694.     gscm_2_double (obj)
  695.          SCM obj;
  696.  
  697.     unsigned long
  698.     gscm_2_ulong (out, obj)
  699.          SCM obj;
  700.  
  701.     long
  702.     gscm_2_long (obj)
  703.          SCM obj;
  704.  
  705.     Convert Scheme objects to numbers.
  706.  
  707.  
  708.  
  709. * gscm_str, gscm_str0
  710.     
  711.     SCM
  712.     gscm_str (str, len)
  713.          char * str;
  714.          int len;
  715.     
  716.     Copy a string into a new Scheme object.
  717.  
  718.  
  719.     SCM
  720.     gscm_str0 (str)
  721.  
  722.     Copy a 0-terminated string into a new Scheme object.
  723.  
  724.  
  725.  
  726. * gscm_2_str
  727.  
  728.     void
  729.     gscm_2_str (chars, len, obj)
  730.          char ** chars;
  731.          int * len;
  732.          SCM * obj;
  733.  
  734.     Return data from a Scheme string.
  735.  
  736.       *******************************************
  737.       * NOTE!!! The obj parameter is passed by  *
  738.       *        _address_, not by value.        *
  739.       *******************************************
  740.  
  741.     The data returned still `belongs' to the Scheme object.
  742.     When the scope of the variable who's address is passed as OBJ
  743.     is left, the string data becomes invalid (it may be garbage
  744.     collected at any time).  If you need the data to persist longer
  745.     than that, you must make a private copy.
  746.  
  747.     The data returned also becomes invalid if you assign a new
  748.     value to the SCM variable whose address was passed. 
  749.     For example, this code is buggy:
  750.  
  751.         {
  752.           char * str;
  753.           int len;
  754.  
  755.           gscm_2_str (&str, &len, scmobj);
  756.  
  757.           str[0] = 'a';   /* this is fine. */
  758.  
  759.           scmobj = some_other_obj;    /* assigning to scmobj invalidates STR */
  760.  
  761.           str[0] = 'b';  /* this is a bug! str is no longer valid. */
  762.         }
  763.  
  764.  
  765.  
  766. * gscm_is_eq, gscm_is_eqv gscm_is_equal
  767.  
  768.     int gscm_is_eq (SCM a, SCM b)
  769.     int gscm_is_eqv (SCM a, SCM b)
  770.     int gscm_is_equal (SCM a, SCM b)
  771.  
  772.     Return 0 or 1 according to whether A and B satisfy the 
  773.     indicated equivalance.
  774.  
  775.  
  776.  
  777. * gscm_bool, gscm_2_bool
  778.  
  779.     SCM gscm_bool (int cbool);
  780.  
  781.     Return #t or #f according to CBOOL: 0 for #f, #t otherwise.
  782.  
  783.  
  784.     int gscm_2_bool (SCM bool);
  785.  
  786.     Return 0 if BOOL is #f, otherwise, return 1.
  787.  
  788.     
  789.  
  790.  
  791. * gscm_symbol, gscm_tmp_symbol
  792.  
  793.     SCM gscm_symbol (char * name, int len);
  794.  
  795.     Return a normal symbol.  The second form is for 0-terminated names.
  796.  
  797.  
  798.     SCM gscm_tmp_symbol (char * name, int len)
  799.  
  800.     Return a new symbol that is not interned in any obarray.
  801.  
  802.  
  803.  
  804.  
  805. * gscm_vector, gscm_vref, gscm_vset
  806.  
  807.     SCM gscm_vector (int size, SCM init)
  808.  
  809.     Create a new vector object, filled with INIT.
  810.  
  811.     SCM gscm_vref (SCM vector, int index)
  812.     void gscm_vset (SCM vector, int index, SCM value)
  813.  
  814.     Accessor and modifier for vectors.
  815.  
  816.  
  817. * gscm_obj_length
  818.  
  819.     int gscm_obj_length (SCM obj)
  820.  
  821.     Return the length of an object or -1.
  822.  
  823.     Length is defined for lists, strings, symbols (treated as strings),
  824.     and vectors.  For any type for which length is not defined, -1
  825.     is returned.
  826.  
  827.  
  828.  
  829. * gscm_make_subr, gscm_curry
  830.  
  831. It has already been shown how to define new built-ins as part of the 
  832. initializing the interpreter.   It is possible, in addition, to create
  833. new anonymous functions on-the-fly during the execution of built-in
  834. functions:
  835.  
  836.     SCM gscm_make_subr (int req, int opt, int varp, SCM (*fn)())
  837.  
  838.     Return an anonymous procedure object for the C function FN.
  839.     The REQ, OPT, and VARP parameters are documented under
  840.     the function gscm_define_procedure (see above).
  841.     
  842.  
  843. gscm_make_subr creates a new anonymous procedure that, when invoked,
  844. calls a C function.  Sometimes it is useful (for example, when
  845. creating ``call-backs'') to specify values that will be passed for some
  846. of the parameters to that function.  That can be done with this function:
  847.  
  848.  
  849.     SCM gscm_curry (SCM procedure, SCM first_arg)
  850.  
  851.     Return a new procedure that is the curry of PROCEDURE with FIRST_ARG.
  852.  
  853.     When the new procedure is invoked, it calls the original
  854.     procedure, supplying FIRST_ARG as the first argument.  If the
  855.     new procedure is passed additional arguments, they are
  856.     forwarded to the original procedure as the second and
  857.     subsequent argument.
  858.  
  859.  
  860. * gscm_catch, gscm_throw, gscm_dynamic_wind
  861.  
  862.     SCM gscm_catch (SCM tag, SCM thunk, SCM handler)
  863.  
  864.     Equivalent to the Scheme code:
  865.  
  866.         (catch-wind tag thunk handler)
  867.  
  868.  
  869.  
  870.  
  871.  
  872.     SCM gscm_throw (SCM tag, SCM value)
  873.  
  874.     Equivalent to the Scheme code:
  875.     
  876.         (throw tag value)
  877.     
  878.     Like the Scheme function, this C function never returns.
  879.  
  880.  
  881.  
  882.     SCM gscm_dynamic_wind (SCM entering, SCM thunk, SCM leaving)
  883.     
  884.     Equivalent to the Scheme code:
  885.     
  886.         (dynamic-wind entering thunk leaving)
  887.     
  888.     Like the Scheme function, this C function never returns.
  889.  
  890.  
  891. [[[Some sample code is needed that illustrates using catch/throw, d-w, 
  892.    wrap, and curry.]]]
  893.  
  894.  
  895.  
  896. * gscm_apply
  897.  
  898.     SCM gscm_apply (SCM procedure, SCM list_of_args)
  899.  
  900.     Apply PROCEDURE to the elements of LIST_OF_ARGS, returning the result.
  901.  
  902.  
  903.  
  904. * gscm_error
  905.  
  906. All of the functions above have the property that if they are passed a
  907. Scheme object of incorrect type, they signal an error and do not
  908. return (they long jump to the root of Scheme evaluation where the
  909. error handler decides what to do next).
  910.  
  911. Built-in functions can themselves signal errors using this function:
  912.  
  913.  
  914.     SCM gscm_error (char * message, SCM args)
  915.  
  916.     The same as `(apply error (cons message args))'
  917.  
  918.     Perform an immediate, non-local exit from the calling procedure,
  919.     signaling an error.  
  920.  
  921.     The arguments are an error message and an arbitrary collection
  922.     of Scheme objects.
  923.  
  924.  
  925.  
  926.  
  927.   ADDING NEW TYPES TO GUILE
  928.   =========================
  929.  
  930. * gscm_alloc_obj, gscm_unwrap_obj
  931.  
  932. These functions are used to define new types of Scheme objects, to
  933. instantiate them, and to access their data.
  934.  
  935. The header file "guile.h" includes this definition:
  936.     
  937.     struct gscm_type
  938.     {
  939.        char * name;
  940.        int equal_proc (SCM a, SCM b);
  941.        int print_proc (SCM obj, SCM port, int writingp);
  942.        void die_fn (SCM obj);
  943.     };
  944.  
  945.  
  946. To define a new type of Scheme object, you must create one permanent
  947. instance of this structure type, and fill it in with data and functions 
  948. that describe your new type.
  949.  
  950. The TYPE_NAME is a 0 terminated string used only for debugging and
  951. when using the default printed representation of objects
  952. (e.g. `#<type-name 0x1000298>').
  953.  
  954. You may provide EQUAL_PROC, which implements equal? for two objects of
  955. this type.  If set to 0, then equal? for this type is no different
  956. than eq?.
  957.  
  958. You may provide PRINT_PROC.  This function is called to WRITE objects
  959. of this type and to DISPLAY them (WRITE and DISPLAY are two standard
  960. Scheme procedures for externalizing object).  The parameter WRITINGP
  961. indicates which kind of call is being made (0 for DISPLAY, otherwise,
  962. WRITE).  The PORT parameter is a Scheme port on which to print the
  963. object.  SCM's port i/o functions for writing to ports are described
  964. later in this document.  The parameter OBJ is the value to print.
  965. PORT should return 0 only if it has not printed the object, 1
  966. otherwise.  If 0 is returned, or if NULL is specified as the
  967. PRINT_PROC, a default print routine is used.
  968.  
  969. The DIE_FN is called when an instance of one of these objects has been
  970. garbage collected.  It is passed a reference to the dying object.
  971. During the execution of the DIE_FN, it is important to not save any
  972. references to the dying object.  Only resource de-allocation is
  973. permitted from inside a DIE_FN.  DIE_FN's are never asynchronously
  974. interrupted, and they may not use GSCM_DEFER_INTS / GSCM_ALLOW_INTS.
  975. DIE_FN's may not call any gscm function other than `gscm_unwrap' (see
  976. below).
  977.  
  978.  
  979.     SCM gscm_alloc_obj (struct gscm_type * type, int size);
  980.  
  981.     Allocate storage for a new Scheme object of a type you define.
  982.     The object is allocated SIZE bytes of storage, initialized
  983.     to all 0's.  The encapsulation of the object as an SCM value
  984.     is returned.
  985.  
  986.     Object's are currently restricted to be fewer than 2^15 bytes
  987.     in size.  If you need a larger object, allocate it using
  988.     malloc and store a pointer to that object in your scheme
  989.     object.  See the notes above concerning GSCM_DEFER_INTS
  990.     and GSCM_ALLOW_INTS before using malloc in this way.
  991.  
  992.  
  993.     char * gscm_unwrap_obj (struct gscm_type * type, SCM * obj)
  994.  
  995.       *******************************************
  996.       * NOTE!!! The obj parameter is passed by  *
  997.       *        _address_, not by value.        *
  998.       *******************************************
  999.  
  1000.     (See the documentation of gscm_2_str for an explanation
  1001.      of this warning).
  1002.  
  1003.     Retrieve the data Encapsulated in a Scheme object.
  1004.     If OBJ is not of type TYPE, then an error is signaled.
  1005.  
  1006.  
  1007.     
  1008.     struct gscm_type * type gscm_get_type (SCM * obj)
  1009.     
  1010.       *******************************************
  1011.       * NOTE!!! The obj parameter is passed by  *
  1012.       *        _address_, not by value.        *
  1013.       *******************************************
  1014.  
  1015.     (See the documentation of gscm_2_str for an explanation
  1016.      of this warning).
  1017.  
  1018.     Return the type structure associated with a Scheme object.
  1019.     If the object is not of a type defined using gscm_alloc_obj,
  1020.     then NULL is returned.
  1021.  
  1022.  
  1023. Storage allocated by gscm_alloc_obj is one of the three aforementioned
  1024. safe locations to store data of SCM type (See the section ``The Type
  1025. SCM'').
  1026.  
  1027.  
  1028.  
  1029. * Print Functions: 
  1030.   gscm_print_obj, gscm_lputc, gscm_lputs, gscm_lfwrite, gscm_lflush
  1031.  
  1032. In the preceding section you were shown how to add new types to Scheme
  1033. which include in their definition a print function -- a function that 
  1034. does the work of the standard Scheme procedures WRITE and DISPLAY for
  1035. your type.
  1036.  
  1037. Your print function is passed the object to print and a Scheme port
  1038. on which to print its output.  Here are some functions which you can 
  1039. use to write data to a Scheme port.  [In the future, there will be more.]
  1040.  
  1041.     void gscm_print_obj (SCM obj, SCM port, int writingp)
  1042.  
  1043.     Print OBJ on PORT, either displaying or writing according to WRITINGP.
  1044.  
  1045.  
  1046.     void gscm_putc (int c, SCM port)
  1047.  
  1048.     Output a single character on a port.
  1049.  
  1050.  
  1051.  
  1052.     void gscm_puts (char * s, SCM port)
  1053.  
  1054.     Output a 0-terminated string on a port.
  1055.  
  1056.  
  1057.  
  1058.     int gscm_fwrite (char *ptr, sizet size, sizet nitems, SCM port)
  1059.  
  1060.     Comparable to fwrite, but for Scheme ports.
  1061.  
  1062.  
  1063.  
  1064.     void gscm_flush (SCM port)
  1065.  
  1066.     Comparable to the scheme procedure FORCE-OUTPUT.
  1067.  
  1068.  
  1069.  
  1070.  
  1071.   TIPS FOR DOCUMENTATION STRINGS
  1072.   ==============================
  1073.  
  1074. Here are some tips for the writing of documentation strings.
  1075.  
  1076.    * Every command, function or variable intended for users to know
  1077.      about should have a documentation string.
  1078.  
  1079.    * An internal subroutine of a Lisp program need not have a
  1080.      documentation string, and you can save space by using a comment
  1081.      instead.
  1082.  
  1083.    * The first line of the documentation string should consist of one
  1084.      or two complete sentences which stand on their own as a summary.
  1085.      In particular, start the line with a capital letter and end with a
  1086.      period.
  1087.  
  1088.      The documentation string can have additional lines which expand on
  1089.      the details of how to use the function or variable.  The
  1090.      additional lines should be made up of complete sentences also, but
  1091.      they may be filled if that looks good.
  1092.  
  1093.    * Do not start or end a documentation string with whitespace.
  1094.  
  1095.    * Format the documentation string so that it fits in an Emacs window
  1096.      on an 80 column screen.  It is a good idea for most lines to be no
  1097.      wider than 60 characters.  The first line can be wider if
  1098.      necessary to fit the information that ought to be there.
  1099.  
  1100.      However, rather than simply filling the entire documentation
  1101.      string, you can make it much more readable by choosing line breaks
  1102.      with care.  Use blank lines between topics if the documentation
  1103.      string is long.
  1104.  
  1105.    * *Do not* indent subsequent lines of a documentation string so that
  1106.      the text is lined up in the source code with the text of the first
  1107.      line.  This looks nice in the source code, but looks bizarre when
  1108.      users view the documentation.  Remember that the indentation
  1109.      before the starting double-quote is not part of the string!
  1110.  
  1111.    * A variable's documentation string should start with `*' if the
  1112.      variable is one that users would want to set interactively often.
  1113.      If the value is a long list, or a function, or if the variable
  1114.      would only be set in init files, then don't start the
  1115.      documentation string with `*'.  *Note Defining Variables::.
  1116.  
  1117.    * The documentation string for a variable that is a yes-or-no flag
  1118.      should start with words such as "Non-nil means...", to make it
  1119.      clear both that the variable only has two meaningfully distinct
  1120.      values and which value means "yes".
  1121.  
  1122.    * When a function's documentation string mentions the value of an
  1123.      argument of the function, use the argument name in capital letters
  1124.      as if it were a name for that value.  Thus, the documentation
  1125.      string of the function `/' refers to its second argument as
  1126.      `DIVISOR'.
  1127.  
  1128.      Also use all caps for meta-syntactic variables, such as when you
  1129.      show the decomposition of a list or vector into subunits, some of
  1130.      which may be variable.
  1131.  
  1132.    * When a documentation string refers to a Lisp symbol, write it as it
  1133.      would be printed (which usually means in lower case), with
  1134.      single-quotes around it.  For example: ``lambda''.  There are two
  1135.      exceptions: write `t' and `nil' without single-quotes.
  1136.  
  1137.    * Don't write key sequences directly in documentation strings.
  1138.      Instead, use the `\\[...]' construct to stand for them.  For
  1139.      example, instead of writing `C-f', write `\\[forward-char]'.  When
  1140.      the documentation string is printed, Emacs will substitute
  1141.      whatever key is currently bound to `forward-char'.  This will
  1142.      usually be `C-f', but if the user has moved key bindings, it will
  1143.      be the correct key for that user.  *Note Keys in Documentation::.
  1144.  
  1145.    * In documentation strings for a major mode, you will want to refer
  1146.      to the key bindings of that mode's local map, rather than global
  1147.      ones.  Therefore, use the construct `\\<...>' once in the
  1148.      documentation string to specify which key map to use.  Do this
  1149.      before the first use of `\\[...]'.  The text inside the `\\<...>'
  1150.      should be the name of the variable containing the local keymap for
  1151.      the major mode.
  1152.  
  1153.  
  1154.